//! # 通配符模式匹配测试
//!
//! 提供消息路由中通配符模式匹配的全面测试覆盖

#[cfg(test)]
mod wildcard_pattern_tests {
    use crate::prelude::*;
    use crate::mock::{MockMessageBus, test_helpers::*};
    use serde_json::json;

    /// 基础通配符测试
    mod basic_wildcard_tests {
        use super::*;

        #[tokio::test]
        async fn test_single_level_wildcard() {
            let bus = MockMessageBus::new();
            let subscriber = bus.subscribe("events.*").await.unwrap();

            // 应该匹配的主题
            let matching_topics = vec![
                "events.login",
                "events.logout", 
                "events.signup",
                "events.delete",
            ];

            for topic in matching_topics {
                let message = create_test_message(topic, json!({"event": topic}));
                bus.publish(message).await.unwrap();
            }

            // 不应该匹配的主题
            let non_matching_topics = vec![
                "events",           // 缺少子级
                "events.user.login", // 多了一级
                "logs.events.login", // 前缀不匹配
                "events.",          // 空子级
            ];

            for topic in non_matching_topics {
                let message = create_test_message(topic, json!({"event": topic}));
                bus.publish(message).await.unwrap();
            }

            // 验证只有匹配的消息被路由
            let published = bus.get_published_messages_for_topic("events.login").await;
            assert_eq!(published.len(), 1);
        }

        #[tokio::test]
        async fn test_multi_level_wildcard() {
            let bus = MockMessageBus::new();
            let subscriber = bus.subscribe("user.**").await.unwrap();

            // 应该匹配的主题
            let matching_topics = vec![
                "user.events",
                "user.events.login",
                "user.profile.update",
                "user.settings.theme.dark",
                "user.notifications.email.sent",
            ];

            for topic in matching_topics {
                let message = create_test_message(topic, json!({"topic": topic}));
                bus.publish(message).await.unwrap();
            }

            // 不应该匹配的主题
            let non_matching_topics = vec![
                "user",             // 主题本身
                "admin.user.events", // 前缀不匹配
                "users.events",     // 复数形式
            ];

            for topic in non_matching_topics {
                let message = create_test_message(topic, json!({"topic": topic}));
                bus.publish(message).await.unwrap();
            }

            let total_published = bus.get_published_messages().await.len();
            assert_eq!(total_published, 8); // 5 + 3
        }

        #[tokio::test]
        async fn test_exact_match() {
            let bus = MockMessageBus::new();
            let subscriber = bus.subscribe("exact.topic.match").await.unwrap();

            // 精确匹配
            let exact_message = create_test_message("exact.topic.match", json!({"exact": true}));
            bus.publish(exact_message).await.unwrap();

            // 不匹配的变体
            let non_matching = vec![
                "exact.topic",
                "exact.topic.match.extra",
                "exact.topic.mismatch",
                "EXACT.TOPIC.MATCH", // 大小写不匹配
            ];

            for topic in non_matching {
                let message = create_test_message(topic, json!({"exact": false}));
                bus.publish(message).await.unwrap();
            }

            let exact_messages = bus.get_published_messages_for_topic("exact.topic.match").await;
            assert_eq!(exact_messages.len(), 1);
            assert_eq!(exact_messages[0].payload()["exact"], true);
        }
    }

    /// 复杂模式测试
    mod complex_pattern_tests {
        use super::*;

        #[tokio::test]
        async fn test_mixed_wildcards() {
            let bus = MockMessageBus::new();
            
            // 混合使用单级和多级通配符
            let subscriber = bus.subscribe("app.*.events.**").await.unwrap();

            let matching_topics = vec![
                "app.user.events.login",
                "app.admin.events.audit.access",
                "app.system.events.startup.complete",
            ];

            let non_matching_topics = vec![
                "app.events.login",        // 缺少中间级别
                "app.user.logs.error",     // events不匹配
                "service.user.events.login", // app不匹配
            ];

            for topic in matching_topics {
                let message = create_test_message(topic, json!({"matches": true}));
                bus.publish(message).await.unwrap();
            }

            for topic in non_matching_topics {
                let message = create_test_message(topic, json!({"matches": false}));
                bus.publish(message).await.unwrap();
            }

            let total_published = bus.get_published_messages().await.len();
            assert_eq!(total_published, 6);
        }

        #[tokio::test]
        async fn test_nested_patterns() {
            let bus = MockMessageBus::new();
            
            // 嵌套模式
            let patterns = vec![
                "service.*.status.*",
                "service.auth.**",
                "service.**.critical",
            ];

            let mut subscribers = vec![];
            for pattern in &patterns {
                let sub = bus.subscribe(pattern).await.unwrap();
                subscribers.push(sub);
            }

            // 测试消息
            let test_cases = vec![
                ("service.api.status.healthy", vec![true, false, false]),
                ("service.auth.login.failed", vec![false, true, false]),
                ("service.db.connection.critical", vec![false, false, true]),
                ("service.cache.status.down", vec![true, false, false]),
                ("service.auth.token.expired.critical", vec![false, true, true]),
            ];

            for (topic, should_match) in test_cases {
                let message = create_test_message(topic, json!({"topic": topic}));
                bus.publish(message).await.unwrap();
                
                // 这里只是发布消息，实际的匹配逻辑在MockMessageBus内部
            }
        }

        #[tokio::test]
        async fn test_wildcard_at_different_positions() {
            let bus = MockMessageBus::new();

            let patterns = vec![
                "*.events.login",      // 开头通配符
                "user.*.login",        // 中间通配符
                "user.events.*",       // 结尾通配符
                "**.critical",         // 开头多级通配符
                "user.**",             // 结尾多级通配符
            ];

            for pattern in patterns {
                let subscriber = bus.subscribe(&pattern).await.unwrap();
                
                let test_topic = match pattern {
                    "*.events.login" => "admin.events.login",
                    "user.*.login" => "user.auth.login", 
                    "user.events.*" => "user.events.success",
                    "**.critical" => "system.db.connection.critical",
                    "user.**" => "user.profile.settings.theme",
                    _ => "test.topic"
                };

                let message = create_test_message(test_topic, json!({"pattern": pattern}));
                bus.publish(message).await.unwrap();
            }
        }
    }

    /// 边界条件测试
    mod edge_case_tests {
        use super::*;

        #[tokio::test]
        async fn test_empty_and_special_topics() {
            let bus = MockMessageBus::new();

            // 特殊主题名称
            let special_topics = vec![
                "topic.with.dots.many.levels",
                "single",
                "a.b",
                "very.long.topic.name.with.many.segments.for.testing.purposes",
            ];

            // 对应的模式
            let patterns = vec![
                "topic.with.dots.**",
                "*",
                "a.*",
                "very.long.topic.**",
            ];

            for (topic, pattern) in special_topics.iter().zip(patterns.iter()) {
                let subscriber = bus.subscribe(pattern).await.unwrap();
                let message = create_test_message(topic, json!({"special": true}));
                bus.publish(message).await.unwrap();
            }
        }

        #[tokio::test]
        async fn test_overlapping_patterns() {
            let bus = MockMessageBus::new();

            // 重叠的模式
            let overlapping_patterns = vec![
                "events.*",
                "events.user.*",
                "events.**",
                "*.user.*",
            ];

            for pattern in overlapping_patterns {
                let _subscriber = bus.subscribe(&pattern).await.unwrap();
            }

            // 发布一个会匹配多个模式的消息
            let message = create_test_message("events.user.login", json!({"overlapping": true}));
            bus.publish(message).await.unwrap();

            // 验证订阅者数量
            let subscriber_count = bus.get_subscriber_count("events.user.login").await;
            assert!(subscriber_count > 0);
        }

        #[tokio::test]
        async fn test_invalid_pattern_handling() {
            let bus = MockMessageBus::new();

            // 可能有问题的模式（在实际实现中可能需要验证）
            let potentially_problematic = vec![
                "**.**",           // 连续多级通配符
                "*.*.*.*.*.*",     // 大量单级通配符
                "topic.*.*.end",   // 多个连续单级通配符
                ".**.",            // 通配符与点的组合
            ];

            for pattern in potentially_problematic {
                // 在Mock实现中，这些都应该能工作
                let result = bus.subscribe(&pattern).await;
                
                // 根据实际的验证逻辑，这些可能成功或失败
                // 这里我们只是测试系统不会崩溃
                match result {
                    Ok(_) => println!("模式 '{}' 被接受", pattern),
                    Err(e) => println!("模式 '{}' 被拒绝: {}", pattern, e),
                }
            }
        }
    }

    /// 性能相关的模式测试
    mod pattern_performance_tests {
        use super::*;
        use std::time::Instant;

        #[tokio::test]
        async fn test_pattern_matching_performance() {
            let bus = MockMessageBus::new();

            // 创建大量不同的模式
            for i in 0..100 {
                let pattern = format!("perf.test.{}.events.*", i);
                let _subscriber = bus.subscribe(&pattern).await.unwrap();
            }

            // 测试消息匹配性能
            let start = Instant::now();
            
            for i in 0..1000 {
                let topic = format!("perf.test.{}.events.action", i % 100);
                let message = create_test_message(&topic, json!({"perf": i}));
                bus.publish(message).await.unwrap();
            }

            let duration = start.elapsed();
            println!("模式匹配性能: 1000条消息用时 {:?}", duration);

            // 验证性能在合理范围内
            assert!(duration.as_millis() < 1000, "模式匹配性能太慢: {:?}", duration);
        }

        #[tokio::test]
        async fn test_complex_pattern_scalability() {
            let bus = MockMessageBus::new();

            // 创建复杂的嵌套模式
            let complex_patterns = vec![
                "app.*.service.*.events.**",
                "system.**.status.*.health.**", 
                "user.*.profile.**.settings.*",
                "data.**.processing.*.result.**",
            ];

            for pattern in complex_patterns {
                let _subscriber = bus.subscribe(&pattern).await.unwrap();
            }

            // 发布大量消息测试可扩展性
            let start = Instant::now();
            
            for i in 0..500 {
                let topics = vec![
                    format!("app.auth.service.login.events.success.{}", i),
                    format!("system.db.cache.status.redis.health.good.{}", i),
                    format!("user.{}.profile.avatar.settings.theme", i),
                    format!("data.batch.{}.processing.csv.result.completed", i),
                ];

                for topic in topics {
                    let message = create_test_message(&topic, json!({"batch": i}));
                    bus.publish(message).await.unwrap();
                }
            }

            let duration = start.elapsed();
            println!("复杂模式可扩展性测试: 2000条消息用时 {:?}", duration);
        }
    }

    /// 实际使用场景测试
    mod real_world_scenarios {
        use super::*;

        #[tokio::test]
        async fn test_microservice_event_routing() {
            let bus = MockMessageBus::new();

            // 微服务事件路由模式
            let service_patterns = vec![
                "user-service.events.**",      // 用户服务所有事件
                "order-service.*.created",     // 订单创建事件
                "payment-service.**.failed",   // 支付失败事件
                "notification-service.*.*",    // 通知服务事件
            ];

            for pattern in service_patterns {
                let _subscriber = bus.subscribe(&pattern).await.unwrap();
            }

            // 模拟微服务事件
            let events = vec![
                "user-service.events.user.registered",
                "user-service.events.profile.updated", 
                "order-service.order.created",
                "order-service.item.created",
                "payment-service.card.payment.failed",
                "payment-service.bank.transfer.failed",
                "notification-service.email.sent",
                "notification-service.sms.delivered",
            ];

            for event in events {
                let message = create_test_message(event, json!({"service_event": event}));
                bus.publish(message).await.unwrap();
            }

            let total_published = bus.get_published_messages().await.len();
            assert_eq!(total_published, 8);
        }

        #[tokio::test]
        async fn test_hierarchical_logging() {
            let bus = MockMessageBus::new();

            // 分层日志模式
            let log_patterns = vec![
                "logs.error.**",        // 所有错误日志
                "logs.*.critical",      // 所有critical级别
                "logs.app.*.debug",     // 应用debug日志
                "logs.system.**",       // 所有系统日志
            ];

            for pattern in log_patterns {
                let _subscriber = bus.subscribe(&pattern).await.unwrap();
            }

            // 模拟各种日志事件
            let log_events = vec![
                "logs.error.database.connection",
                "logs.error.api.timeout", 
                "logs.warning.critical",
                "logs.info.critical",
                "logs.app.auth.debug",
                "logs.app.cache.debug",
                "logs.system.cpu.high",
                "logs.system.memory.usage.alert",
            ];

            for log_event in log_events {
                let message = create_test_message(log_event, json!({"log_level": log_event}));
                bus.publish(message).await.unwrap();
            }
        }

        #[tokio::test]
        async fn test_iot_sensor_data_routing() {
            let bus = MockMessageBus::new();

            // IoT传感器数据路由
            let sensor_patterns = vec![
                "sensors.temperature.**",    // 所有温度传感器
                "sensors.*.alert",          // 所有警报
                "sensors.building.*.data",  // 建筑物传感器数据
                "sensors.**.critical",      // 所有critical级别
            ];

            for pattern in sensor_patterns {
                let _subscriber = bus.subscribe(&pattern).await.unwrap();
            }

            // 模拟传感器数据
            let sensor_data = vec![
                "sensors.temperature.room1.data",
                "sensors.temperature.room1.alert",
                "sensors.humidity.room2.alert",
                "sensors.building.floor1.data",
                "sensors.building.floor2.data", 
                "sensors.fire.detector.critical",
                "sensors.smoke.hallway.critical",
            ];

            for data in sensor_data {
                let message = create_test_message(data, json!({"sensor": data}));
                bus.publish(message).await.unwrap();
            }
        }
    }
}